<?php

namespace app\listener;

use app\model\Tweet;
use app\model\User;

class SendTweetReplyNotificationListener
{
    /**
     * 处理推文被回复的事件
     *
     * @param Tweet $originalTweet 被回复的推文
     * @param User $replyingUser 发出回复的用户
     * @return void
     */
    public function handle(Tweet $originalTweet, User $replyingUser): void
    {
        // 如果用户回复自己的推文，则不发送通知
        if ($originalTweet->user_id === $replyingUser->id) {
            return;
        }

        $authorId = $originalTweet->user_id;
        $message = htmlspecialchars($replyingUser->username, ENT_QUOTES, 'UTF-8') . " 回复了你的动态。";

        $notificationId = $_SESSION['next_notification_id']++;

        $_SESSION['notifications'][$notificationId] = [
            'id' => $notificationId,
            'user_id' => $authorId, // 应该接收通知的用户ID
            'message' => $message,
            'link' => '/tweet/view/' . $originalTweet->id,
            'is_read' => false,
            'timestamp' => time(),
        ];

        error_log("通知已为用户 {$authorId} 创建: {$message}");
    }
}
